import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import { addRouter } from '@/utils/addRouter'
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // 获取Token
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // 如果已经登录过了要去的路径是/login,则调到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 从Store中获取用户信息
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        // 有的话就放行
        next()
      } else {
        try {
          // 没有的话就调接口获取用户信息
          await store.dispatch('user/getUserInfo').then(data => { // 请求路由数据
            gotoRouter(to, next, data.menuTrees)
          })
          // 然后放行
        } catch (error) {
          // 如果有异常清token,跳转到登录页
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login`)
          NProgress.done()
        }
      }
      // 从Store中获取用户按钮信息
      const hasGetMenuBtton = store.getters.menus
      if (hasGetMenuBtton) {
        // 有的话就放行
        next()
      } else {
        // 没有的话就调接口获取用户信息
        await store.dispatch('user/getUserMenuForButton')
        // 然后放行
        next()
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
function gotoRouter(to, next, hasRouterData) {
  try {
    // 这个是动态的部分
    const Routers = addRouter(hasRouterData) // 解析路由
    const newRouters = router.options.routes.concat(Routers) // 合并本来的菜单和获取的菜单信息
    router.options.routes = newRouters
    router.addRoutes(newRouters) // 动态添加路由
    next(`/`)
  } catch (error) {
    store.dispatch('user/resetToken')
    Message.error(error || 'Has Error')
    next(`/login`)
    NProgress.done()
  }
}
